  <template>
    <el-card shadow="never" class="border-0">
      <!-- 搜索 -->
      <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="船舶名称">
              <el-input v-model="searchForm.name" placeholder="船舶名称" @keyup.enter.native="initTableData(1)" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <div class="flex items-center justify-end">
              <el-button type="primary" @click="initTableData(1)">搜索</el-button>
              <el-button @click="resetSearchForm">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>


      <!-- 新增|刷新 -->
      <div class="flex items-center justify-between mb-4">
        <div>
          <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
        </div>

        <el-tooltip effect="dark" content="刷新数据" placement="top">
          <el-button text @click="initTableData">
            <el-icon :size="20">
              <Refresh />
            </el-icon>
          </el-button>
        </el-tooltip>
      </div>

      <!-- 表格数据 -->
      <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">

        <el-table-column label="船舶名称" width="170" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.name }}
          </template>
        </el-table-column>
        <el-table-column label="船舶类型" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ formatShipType(row.shipType) }}
          </template>
        </el-table-column>
        <el-table-column label="IMO" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.imo }}
          </template>
        </el-table-column>
        <el-table-column label="MMSI" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.mmsi }}
          </template>
        </el-table-column>
        <el-table-column label="归属项目" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.projectName }}
          </template>
        </el-table-column>

        <el-table-column label="船东公司" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.shipownerCompany }}
          </template>
        </el-table-column>

        <el-table-column label="船管公司" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.shipmanagementCompany }}
          </template>
        </el-table-column>

        <el-table-column label="创建日期" align="center" width="110" show-overflow-tooltip>
          <template #default="{ row }">
            {{ dateFormatterDay(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <small v-if="scope.row.super == 1" class="text-sm text-gray-500">暂无操作</small>
              <div v-else>
                <el-button type="primary" size="small" text @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="primary" size="small" text @click="clickWorkOrderBtn(scope.row)">工单</el-button>
                <el-popconfirm title="是否要删除该设备？" confirmButtonText="确认" cancelButtonText="取消"
                  @confirm="handleDelete(scope.row.id)">
                  <template #reference>
                    <el-button text type="primary" size="small">删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="flex items-center justify-center mt-5">
        <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
          :page-size="limit" @current-change="initTableData" />
      </div>

      <!-- 新增|修改弹窗 -->
      <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">

        <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">

          <el-form-item label="船舶名称" prop="name">
            <el-input v-model="form.name" placeholder="船舶名称"></el-input>
          </el-form-item>

          <el-form-item label="IMO">
            <el-input v-model="form.imo" placeholder="IMO"></el-input>
          </el-form-item>

          <el-form-item label="MMSI">
            <el-input v-model="form.mmsi" placeholder="MMSI"></el-input>
          </el-form-item>

          <el-form-item label="船舶类型" prop="shipType">
            <el-select v-model="form.shipType" filterable placeholder="请选择船舶类型">
              <el-option v-for="item in shipTypeList" :key="item.code" :label="item.description" :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="归属项目" prop="projectName">
            <el-autocomplete v-model="form.projectName" placeholder="请输入归属项目" :fetch-suggestions="fetchProjectName"
              @select="handleProjectSelect">
              <template #default="{ item }">
                <span>{{ item.value }}</span>
              </template>
            </el-autocomplete>
          </el-form-item>

          <el-form-item label="船籍国">
            <el-input v-model="form.flagCountry" placeholder="船籍国"></el-input>
          </el-form-item>

          <el-form-item label="船级社">
            <el-input v-model="form.classificationSociety" placeholder="船级社"></el-input>
          </el-form-item>

          <el-form-item label="船东公司">
            <el-input v-model="form.shipownerCompany" placeholder="船东公司"></el-input>
          </el-form-item>

          <el-form-item label="船管公司">
            <el-input v-model="form.shipmanagementCompany" placeholder="船管公司"></el-input>
          </el-form-item>
        </el-form>
      </FormDrawer>

    </el-card>
  </template>

<script setup>
import { ref, reactive, computed, onMounted,onBeforeUnmount } from "vue"
import FormDrawer from "~/components/FormDrawer.vue";
import { toast } from "~/composables/util"
import { dateFormatterDay } from '~/utils/common.js'
import { shipList,addShip,updateShip,deleteShip,checkNamePrefix } from "~/api/supply"
import { api_project_constant } from "~/api/ordersApi"
import { checkShipNameChinese } from '~/utils/validate.js'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'

//store存储
const store = useStore()
// 全局路由
const router = useRouter()

// 表格分页数据
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)

//船舶类型常量列表
const shipTypeList = ref([])



// 查询条件
const searchForm = reactive({
  name: null,
  page: currentPage.value,
  size: limit.value,
})
// 重置搜索框
const resetSearchForm = () => {
  searchForm.name = null
  initTableData(1)
}

// 生命周期函数
onMounted(() => {
  if (localStorage.getItem('shipSearch')) {
    const tempForm = JSON.parse(localStorage.getItem('shipSearch'));
    Object.assign(searchForm, tempForm);
  }
  // 恢复保存的页码
  const savedPage = localStorage.getItem('shipCurrentPage');
  if (savedPage) {
    currentPage.value = parseInt(savedPage);
  }
  
  //获取字典数据
  getSelectData()
  //初始化列表数据
  initTableData()
})

onBeforeUnmount(() => {
  localStorage.setItem('shipSearch', JSON.stringify(searchForm));
  localStorage.setItem('shipCurrentPage', currentPage.value.toString());
})
// 获取数据
function initTableData(p = null) {
  //指定页码是否为空
  if (typeof p == "number") {
    currentPage.value = p
  }

  loading.value = true
  searchForm.page = currentPage.value

  shipList(searchForm)
    .then(res => {
      if (res) {
        tableData.value = res.records
        total.value = res.total
      } else {
        tableData.value = []
        total.value = 0
      }
    })
    .finally(() => {
      loading.value = false
    })
}

// 删除
const handleDelete = (id) => {
  loading.value = true
  deleteShip(id).then(res => {
      toast("删除成功")
      initTableData()
  }).finally(() => {
      loading.value = false
  })
}

// 表单部分
// 是否是编辑弹窗
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "编辑" : "新增")
const formDrawerRef = ref(null)
const formRef = ref(null)
const form = reactive({
    name: null,
    imo: null,
    mmsi: null,
    flagCountry: null,
    classificationSociety: null,
    shipownerCompany: null,
    shipmanagementCompany: null,
    shipType: null,
    projectName: null,
    projectId: null
})

// 新增按钮点击事件
const handleCreate = () => {
  //修改标记置为0
  editId.value = 0
  resetForm({
    id: null,
    name: null,
    imo: null,
    mmsi: null,
    flagCountry: null,
    classificationSociety: null,
    shipownerCompany: null,
    shipmanagementCompany: null,
    shipType: null,
    projectName: null,
    projectId: null
  })
  //打开弹窗
  formDrawerRef.value.open()
}
//执行表单校验
const rules = {
  name: [
    { validator: checkShipNameChinese, required: true, trigger: 'change' }
  ],
  shipType: [
    { required: true, message: '船舶类型不能为空', trigger: 'change' }
  ],
  projectName: [
    { required: true, message: '归属项目不能为空', trigger: 'change' }
  ]
}

//提交表单
const handleSubmit = () => {
  //表单校验
  formRef.value.validate((valid) => {
    if (!valid) return

    //console.log(JSON.stringify(form))

    //loading
    formDrawerRef.value.showLoading()

    //根据是否是修改标记，判断执行新增接口还是修改接口
    const fun = editId.value ? updateShip(editId.value, form):addShip(form)
    fun.then(res => {
        toast(drawerTitle.value + "成功")
        //修改刷新当前页，新增刷新第一页
        initTableData(editId.value ? false : 1)
        formDrawerRef.value.close()
    }).finally(() => {
        //close loading
        formDrawerRef.value.hideLoading()
      })
  })
}

// 重置表单
function resetForm(row = false) {
  if (formRef.value) formRef.value.resetFields()
  if (row) {
    for (const key in form) {
      form[key] = row[key]
    }
  }
}

// 编辑
const handleEdit = (row) => {
  editId.value = row.id
  resetForm(row)
  formDrawerRef.value.open()
}

// 列表按钮
const clickWorkOrderBtn = (row) => {
    store.commit("SetShipId", row.id)
    
    // 保存当前页码到localStorage
    localStorage.setItem('shipCurrentPage', currentPage.value.toString())

    //跳转界面
    router.push({
        path: '/shipDetail',
    });
}

const fetchProjectName = (query, cb) => {
      if (query === null || query.trim() === '' || query ==='null') {
        return;
      }
      checkNamePrefix(query)
        .then(res => {
          const projects = res;
          const results = projects.map(project => ({
            value: project.projectName,
            id: project.projectId,
          }));
          cb(results);
        })
        .catch(err => {
          console.error('获取项目名称失败:', err);
        });
};

const handleProjectSelect = (item) => {
  // 处理选择项目后的逻辑
  form.projectName = item.value;
  form.projectId = item.id;
};

const formatShipType = (shipType) => {
    return shipTypeList.value.find(x => x.code == shipType)?.description || shipType
}

// 获取船舶类型常量列表
function getSelectData() {
    api_project_constant().then(res => {
        console.log('constant: ', res)
        shipTypeList.value = res?.shipTypeList
    })
}
</script>
<style lang="scss" scoped>
.operation-buttons {
  display: flex;
  justify-content: space-between;
}

.operation-buttons .el-button {
  padding-left: 5px;
  padding-right: 5px;
  margin-right: 0;
  /* 调整按钮之间的间距 */
  width: inherit;
}
</style>